<template>
  <div class="graph-analysis-container">
    <!-- 顶部选项卡导航 - 现代化设计 -->
    <div class="main-tabs-container">
      <div class="main-tabs-wrapper">
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'supplyChain' }" 
          @click="handleTabClick({ props: { name: 'supplyChain' } })"
        >
          <el-icon class="tab-icon"><Link /></el-icon>
          <span class="tab-text">产业链上下游</span>
        </div>
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'industryComprehensive' }" 
          @click="handleTabClick({ props: { name: 'industryComprehensive' } })"
        >
          <el-icon class="tab-icon"><TrendCharts /></el-icon>
          <span class="tab-text">行业企业综合分析</span>
        </div>
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'companyRisks' }" 
          @click="handleTabClick({ props: { name: 'companyRisks' } })"
        >
          <el-icon class="tab-icon"><Warning /></el-icon>
          <span class="tab-text">企业风险</span>
        </div>
        <div 
          class="main-tab" 
          :class="{ 'active': activeTab === 'productChain' }" 
          @click="handleTabClick({ props: { name: 'productChain' } })"
        >
          <el-icon class="tab-icon"><Goods /></el-icon>
          <span class="tab-text">产品链技术决策支持</span>
        </div>
      </div>
    </div>

    <!-- 主内容区域 - 左右两栏布局 -->
    <div class="main-content-layout">
      <!-- 左侧查询表单 -->
      <el-card class="query-card" shadow="hover">
        <!-- 供应链查询表单 -->
        <template v-if="activeTab === 'supplyChain'">
          <supply-chain-form 
            :loading="loading"
            @query="handleSupplyChainQuery"
          />
        </template>

        <!-- 行业综合分析表单 -->
        <template v-else-if="activeTab === 'industryComprehensive'">
          <industry-analysis-form
            :loading="loading"
            @query="handleIndustryAnalysisQuery"
          />
        </template>

        <!-- 企业风险查询表单 -->
        <template v-else-if="activeTab === 'companyRisks'">
          <company-risk-form
            :loading="loading"
            @query="handleCompanyRiskQuery"
          />
        </template>

        <!-- 产品链查询表单 -->
        <template v-else-if="activeTab === 'productChain'">
          <product-chain-form
            :loading="loading"
            @query="handleProductChainQuery"
            @key-materials="handleKeyMaterialsQuery"
            @reset="handleProductChainReset"
          />
        </template>
      </el-card>

      <!-- 右侧结果展示 -->
      <el-card class="graph-card" shadow="hover" v-loading="graphLoading">
        <!-- 图谱展示 -->
        <template v-if="showGraph && !showStats && !showKeyMaterials && !showSupplyChainVulnerability && !showSubstituteAnalysis">
          <graph-visualization
            ref="graphVisualization"
            :title="activeTab === 'companyRisks' ? '行业企业风险分布' : getResultTitle"
            :graph-data="graphData"
            :active-tab="activeTab"
            @export="handleGraphExport"
          />
        </template>

        <!-- 行业企业综合分析数据展示 -->
        <template v-else-if="activeTab === 'industryComprehensive'">
          <div v-if="statsLoading" class="loading-placeholder">
            <el-skeleton :rows="10" animated />
          </div>
          <stats-overview
            v-else-if="statsData"
            :data="statsData"
            :key="'stats-overview-' + forceRender"
            @export="handleStatsExport"
          />
          <el-empty 
            v-else 
            description="请在左侧选择行业并点击'查询分析'按钮进行分析" 
          />
        </template>

        <!-- 关键材料分析结果 -->
        <template v-else-if="showKeyMaterials && !showSupplyChainVulnerability && !showSubstituteAnalysis">
          <div class="analysis-actions">
            <el-button 
              type="warning" 
              @click="handleVulnerabilityAnalysis" 
              class="vulnerability-button"
              :title="'分析关键材料的供应链脆弱性'"
            >
              <el-icon><Warning /></el-icon> 供应链脆弱性分析
            </el-button>
            <el-button type="default" @click="returnToProductChain">
              <el-icon><Back /></el-icon> 返回产品链
            </el-button>
          </div>
          <key-materials-result
            :data="keyMaterialsData"
            @export="handleKeyMaterialsExport"
            @substitute-analysis="handleSubstituteAnalysis"
          />
        </template>

        <!-- 供应链脆弱性分析结果 -->
        <template v-else-if="showSupplyChainVulnerability && !showSubstituteAnalysis">
          <div class="analysis-actions">
            <el-button type="default" @click="returnToKeyMaterials">
              <el-icon><Back /></el-icon> 返回关键材料识别
            </el-button>
          </div>
          <supply-chain-vulnerability-result
            :data="supplyChainVulnerabilityData"
            @export="handleSupplyChainVulnerabilityExport"
          />
        </template>

        <!-- 替代路径分析结果 -->
        <template v-else-if="showSubstituteAnalysis">
          <div class="analysis-actions">
            <el-button type="default" @click="returnToKeyMaterials">
              <el-icon><Back /></el-icon> 返回关键材料
            </el-button>
          </div>
          <substitute-analysis-result
            :data="substituteAnalysisData"
            @export="handleSubstituteAnalysisExport"
          />
        </template>

        <!-- 空状态 -->
        <template v-else>
          <el-empty :description="getEmptyDescription" />
        </template>
      </el-card>
    </div>
  </div>
</template>

<script setup>
// 重新导入所有必要的库和组件
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  Link,
  TrendCharts,
  Warning,
  DataBoard,
  Goods,
  Back
} from '@element-plus/icons-vue';

// 导入组件
import GraphVisualization from '@/components/graph-analysis/GraphVisualization.vue';
import SupplyChainForm from '@/components/graph-analysis/SupplyChainForm.vue';
import IndustryAnalysisForm from '@/components/graph-analysis/IndustryAnalysisForm.vue';
import CompanyRiskForm from '@/components/graph-analysis/CompanyRiskForm.vue';
import ProductChainForm from '@/components/graph-analysis/ProductChainForm.vue';
import StatsOverview from '@/components/graph-analysis/StatsOverview.vue';
import KeyMaterialsResult from '@/components/graph-analysis/KeyMaterialsResult.vue';
import SupplyChainVulnerabilityResult from '@/components/graph-analysis/SupplyChainVulnerabilityResult.vue';
import SubstituteAnalysisResult from '@/components/graph-analysis/SubstituteAnalysisResult.vue';

// 导入混入
import { useGraphMixin, useStatsMixin, useKeyMaterialsMixin } from '@/mixins/graph/chart';
import { hasPermission } from '@/utils/permission';

// 导入API
import {
  getSupplyChain,
  getIndustryComprehensiveAnalysis,
  getCompanyRisks,
  getCompanyStats,
  getProductChain,
  getKeyMaterials,
  getSupplyChainVulnerability,
  getSubstituteAnalysis,
  searchProducts
} from '@/api/graphAnalysis';

const router = useRouter();
const route = useRoute();
const activeTab = ref('supplyChain');

// 使用混入
const {
  graphData,
  loading: graphLoading,
  graphContainer,
  isFullscreen,
  toggleFullscreen,
  handleGraphExport
} = useGraphMixin();

// 本地定义showGraph计算属性
const showGraph = computed(() => !!graphData.value && !!graphData.value.nodes && graphData.value.nodes.length > 0);

const {
  statsData,
  loading: statsLoading,
  handleStatsExport
} = useStatsMixin();

const {
  keyMaterialsData,
  loading: keyMaterialsLoading,
  handleKeyMaterialsExport
} = useKeyMaterialsMixin();

// 计算属性
const loading = computed(() => graphLoading.value || statsLoading.value || keyMaterialsLoading.value || substituteAnalysisLoading.value);
const showStats = computed(() => false);
const showKeyMaterials = computed(() => !!keyMaterialsData.value);
const supplyChainVulnerabilityData = ref(null);
const supplyChainVulnerabilityLoading = ref(false);
const showSupplyChainVulnerability = computed(() => !!supplyChainVulnerabilityData.value);
const substituteAnalysisData = ref(null);
const substituteAnalysisLoading = ref(false);
const showSubstituteAnalysis = computed(() => !!substituteAnalysisData.value);
const resultTitle = ref('');
const loadedProducts = ref([]);
const lastProductChainParams = ref(null);
const lastSupplyChainParams = ref(null);

// 添加一个强制渲染标志
const forceRender = ref(0);

const getResultTitle = computed(() => {
  const titles = {
    supplyChain: '产业链上下游分析',
    industryComprehensive: '行业企业综合分析',
    companyRisks: '企业风险分析',
    productChain: '产品链技术决策支持'
  };
  return titles[activeTab.value] || '知识图谱分析';
});

const getEmptyDescription = computed(() => {
  const descriptions = {
    supplyChain: '请输入企业或产品名称查询供应链',
    industryComprehensive: '请选择行业进行综合分析',
    companyRisks: '请输入企业名称查询风险',
    productChain: '请输入产品名称查询技术链',
  };
  return descriptions[activeTab.value] || '暂无数据';
});

// 检查权限
if (!hasPermission('graph:view')) {
  ElMessage.error('您没有知识图谱分析的权限，请联系管理员授权');
  router.push('/dashboard');
}

// 添加全屏变化事件处理函数 - 使用mixin中的isFullscreen
const handleFullscreenChange = () => {
  // 检查当前是否有元素处于全屏状态
  const isCurrentlyFullscreen = !!document.fullscreenElement || 
                             !!document.webkitFullscreenElement || 
                             !!document.mozFullScreenElement || 
                             !!document.msFullscreenElement;
  
  // 更新状态
  if (isFullscreen.value !== isCurrentlyFullscreen) {
    console.log('[GraphAnalysisNew] 全屏状态变化:', isCurrentlyFullscreen);
    isFullscreen.value = isCurrentlyFullscreen;
  }
};

// 在onMounted钩子中检查路由元数据，设置正确的activeTab
onMounted(() => {
  // 首先检查URL查询参数中的tab参数
  const tabFromQuery = route.query.tab;
  
  console.log('[GraphAnalysisNew] onMounted - URL参数检查:', { tab: tabFromQuery });
  
  if (tabFromQuery) {
    console.log('[GraphAnalysisNew] 从URL查询参数设置活动标签页:', tabFromQuery);
    activeTab.value = tabFromQuery;
    // 当从查询参数加载时，确保重置状态 - 只修改源数据，不直接修改计算属性
    graphData.value = null; // 这会使showGraph计算属性变为false
    statsData.value = null;
    keyMaterialsData.value = null;
    supplyChainVulnerabilityData.value = null;
    substituteAnalysisData.value = null;
  } else {
    // 如果没有查询参数，再检查路由元数据
    const tabFromRoute = route.meta.activeTab || 
                      (route.matched && route.matched[0] && route.matched[0].meta.activeTab);
    
    // 如果存在activeTab元数据，设置activeTab的值
    if (tabFromRoute) {
      activeTab.value = tabFromRoute;
      console.log('[GraphAnalysisNew] 从路由元数据设置活动标签页:', tabFromRoute);
    }
  }
  
  // 检查是否有子路由参数 - 只设置标签但不自动查询
  if (route.name === 'IndustryAnalysisTab') {
    activeTab.value = 'industryComprehensive';
    // 移除自动触发查询
  }
  
  // 添加全屏变化事件监听
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.addEventListener('mozfullscreenchange', handleFullscreenChange);
  document.addEventListener('MSFullscreenChange', handleFullscreenChange);

  // 通过控制台打印一些图表相关的信息，用于调试
  console.log('[GraphAnalysisNew] onMounted - 检查图表渲染状态:', {
    'graphData存在': !!graphData.value,
    'showGraph状态': showGraph.value,
    '图表容器': !!graphContainer.value
  });
});

onUnmounted(() => {
  // 移除全屏变化事件监听
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
});

// 事件处理
const handleTabClick = (tab) => {
  console.log('Tab clicked:', tab.props.name);
  
  // 点击前先重置相关数据 - 只修改源数据，不直接修改计算属性
  graphData.value = null; // 这会使showGraph计算属性变为false
  statsData.value = null;
  keyMaterialsData.value = null;
  supplyChainVulnerabilityData.value = null;
  substituteAnalysisData.value = null;
  
  // 更新活动标签
  activeTab.value = tab.props.name;
  
  // 增加强制渲染计数
  forceRender.value += 1;
  
  // 如果是行业分析标签，处理特定路由逻辑
  if (tab.props.name === 'industryComprehensive') {
    // 改为使用子路由而不是完全切换路由
    router.push({
      path: '/graph-analysis',
      query: { tab: 'industryComprehensive', _t: Date.now() } // 添加时间戳确保URL唯一
    });
  } else {
    // 对于其他标签，使用查询参数记录状态
    router.push({
      path: '/graph-analysis',
      query: { tab: tab.props.name, _t: Date.now() } // 添加时间戳确保URL唯一
    });
  }
};

const handleSupplyChainQuery = async (params) => {
  if (!params.companyName) {
    ElMessage.warning('请输入公司名称');
    return;
  }

  loading.value = true;
  graphLoading.value = true;
  lastSupplyChainParams.value = params;

  try {
    console.log('[GraphAnalysisNew] 查询供应链:', params);
    // 确保API调用时使用正确的参数名
    const apiParams = {
      companyName: params.companyName,
      depth: params.depth
    };
    const result = await getSupplyChain(apiParams);
    
    // 重置状态 - 只修改源数据，不直接修改计算属性
    keyMaterialsData.value = null; // 会导致showKeyMaterials计算属性变为false
    supplyChainVulnerabilityData.value = null; // 会导致showSupplyChainVulnerability计算属性变为false
    substituteAnalysisData.value = null; // 会导致showSubstituteAnalysis计算属性变为false
    statsData.value = null; // 会影响statsData相关的计算属性
    
    // 设置图谱数据展示
    graphData.value = result;
    resultTitle.value = `公司[${params.companyName}]供应链图`;
    
    // 增加强制渲染计数，确保视图更新
    forceRender.value += 1;
    
    console.log('[GraphAnalysisNew] 供应链查询成功，数据已更新');
    
    // 使用nextTick确保在DOM更新后执行
    nextTick(() => {
      console.log('[GraphAnalysisNew] 显示状态更新:', {
        showKeyMaterials: showKeyMaterials.value,
        showGraph: showGraph.value,
        showSupplyChainVulnerability: showSupplyChainVulnerability.value,
        showSubstituteAnalysis: showSubstituteAnalysis.value
      });
    });
  } catch (error) {
    console.error('[GraphAnalysisNew] 供应链查询失败:', error);
    ElMessage.error('供应链查询失败: ' + (error.message || '未知错误'));
    // 清除数据而不是直接修改计算属性
    graphData.value = null;
  } finally {
    // 确保无论成功或失败都会重置加载状态
    loading.value = false;
    graphLoading.value = false;
  }
};

const handleIndustryAnalysisQuery = async (params) => {
  try {
    statsLoading.value = true;
    
    // 根据分析维度决定使用哪个API
    let response;
    
    if (params.analysisDimension === 'region') {
      // 区域维度分析
      console.log('[GraphAnalysisNew] 执行区域维度分析，参数:', params);
      response = await getCompanyStats({
        province: params.province,
        industryName: params.industryName
      });
      
      console.log('[GraphAnalysisNew] 区域维度分析原始响应:', response);
      
      // 处理数据格式，将区域数据传给行业分析组件
      if (Array.isArray(response)) {
        console.log('[GraphAnalysisNew] 响应是数组格式，长度:', response.length);
        // 如果已经是数组格式，直接包装
        statsData.value = {
          regionStats: response,
          analysisDimension: 'region'
        };
      } else {
        console.log('[GraphAnalysisNew] 响应是对象格式，尝试提取数组数据');
        // 如果是对象形式，提取数组
        statsData.value = {
          regionStats: response.data || [],
          analysisDimension: 'region'
        };
      }
      
      console.log('[GraphAnalysisNew] 处理后的区域统计数据:', statsData.value);
    } else {
      // 行业维度分析
      console.log('[GraphAnalysisNew] 执行行业维度分析，参数:', params);
      response = await getIndustryComprehensiveAnalysis(params);
      
      console.log('[GraphAnalysisNew] 行业维度分析原始响应:', response);
      
      // 同时获取区域数据作为补充
      console.log('[GraphAnalysisNew] 获取区域补充数据，使用行业:', params.industryName);
      const regionResponse = await getCompanyStats({
        province: params.province,
        industryName: params.industryName
      });
      
      console.log('[GraphAnalysisNew] 区域补充数据原始响应:', regionResponse);
      
      if (response) {
        // 处理数据，添加区域维度
        if (Array.isArray(regionResponse)) {
          console.log('[GraphAnalysisNew] 区域补充响应是数组格式，长度:', regionResponse.length);
          response.regionStats = regionResponse;
        } else if (regionResponse && Array.isArray(regionResponse.data)) {
          console.log('[GraphAnalysisNew] 区域补充响应是对象格式，尝试提取数组数据');
          response.regionStats = regionResponse.data;
        } else {
          console.log('[GraphAnalysisNew] 无法识别的区域补充数据格式，设置为空数组');
          response.regionStats = [];
        }
          
        response.analysisDimension = 'industry';
        response.selectedProvince = params.province || null;
        
        // 设置数据，确保视图更新
        statsData.value = null; // 先设为null，强制重新渲染
        await nextTick();
        statsData.value = response;
        
        // 确保图表在数据设置后有足够时间初始化
        forceRender.value += 1; // 增加强制渲染计数
      }
      
      // 检查区域数据是否成功添加到行业数据中
      if (statsData.value && statsData.value.regionStats) {
        console.log('[GraphAnalysisNew] 最终处理的区域统计数据长度:', statsData.value.regionStats.length);
        if (statsData.value.regionStats.length > 0) {
          console.log('[GraphAnalysisNew] 第一条区域数据示例:', statsData.value.regionStats[0]);
        }
      } else {
        console.warn('[GraphAnalysisNew] 区域统计数据未成功添加到行业数据中');
        // 如果区域数据为空，尝试补充空数组避免undefined错误
        if (statsData.value) {
          statsData.value.regionStats = [];
        }
      }
    }
    
    console.log('[GraphAnalysisNew] 行业/区域分析最终结果:', statsData.value);
    
    // 使用nextTick确保在DOM更新后记录状态
    nextTick(() => {
      console.log('[GraphAnalysisNew] 显示状态更新:', {
        showGraph: showGraph.value,
        showStats: showStats.value,
        showKeyMaterials: showKeyMaterials.value,
        showSupplyChainVulnerability: showSupplyChainVulnerability.value,
        showSubstituteAnalysis: showSubstituteAnalysis.value
      });
    });
    
    // 延迟一段时间再关闭加载状态，确保DOM有足够时间更新
    setTimeout(() => {
      statsLoading.value = false;
    }, 300);
  } catch (error) {
    console.error('[GraphAnalysisNew] 行业分析失败:', error);
    ElMessage.error('分析失败，请稍后重试');
    statsLoading.value = false;
    // 清除数据而不是直接修改计算属性
    statsData.value = null;
  }
};

const handleCompanyRiskQuery = async (params) => {
  try {
    console.log('[GraphAnalysisNew] 接收到的查询参数:', params);
    
    // 确保参数格式正确 - 根据后端接口需要的参数名进行映射
    const formData = {
      industryName: params.industryName, // 接口需要的是industryName
      minRiskCount: params.minRiskCount  // minRiskCount是正确的参数名
    };

    // 清除之前的图表数据
    graphData.value = { nodes: [], relationships: [] };
    graphLoading.value = true;
    
    console.log('[GraphAnalysisNew] 发送到API的参数:', formData);
    
    const response = await getCompanyRisks(formData);
    
    console.log('[GraphAnalysisNew] 企业风险查询结果:', response);
    
    if (!response || !response.riskyCompanies || response.riskyCompanies.length === 0) {
      ElMessage.warning('未找到符合条件的企业');
      graphLoading.value = false;
      return;
    }

    // 构建图表数据
    const nodes = [];
    
    // 添加企业节点
    response.riskyCompanies.forEach((company, index) => {
      // 使用索引确保ID唯一
      const nodeId = `company_${index}`;
      
      // 正确处理公司名称字段 - API返回的是company而不是name
      const companyName = company.company || `企业${index+1}`;
      
      // 处理高新技术企业标识 - API返回的是布尔值
      const isHighTech = Boolean(company.isHighTech);
      
      // 处理风险数量，确保是数值类型
      const riskCount = Number(company.riskCount) || 0;
      
      nodes.push({
        id: nodeId,
        name: companyName,
        category: isHighTech ? 0 : 1, // 分类：0=高新企业，1=普通企业
        value: {
          riskCount: riskCount,
          companyScale: company.companyScale || '未知',
          registeredCapital: company.registeredCapital || '未知',
          province: company.province || '未知',
          isHighTech: isHighTech,
          employeeCount: company.employeeCount || '未知',
          establishYear: company.establishYear || '未知'
        }
      });
    });

    // 构建完整的图表数据对象
    const graphDataObj = {
      nodes: nodes,
      relationships: [], // 根据要求，企业之间没有直接关系
      industryInfo: {
        name: response.industry || params.industryName,
        riskThreshold: response.minRiskThreshold || params.minRiskCount,
        companyCount: response.riskyCompanies.length
      }
    };

    // 稳健的渲染流程
    graphLoading.value = true;
    
    // 先设置数据
    graphData.value = graphDataObj;
    
    // 再确保DOM更新，使用nextTick代替直接修改showGraph
    await nextTick();
    
    // 增加强制渲染计数，确保视图更新
    forceRender.value += 1;
    
    // 短暂延迟后结束加载状态，给图表渲染留出时间
    setTimeout(() => {
      graphLoading.value = false;
      
      // 使用nextTick确保在DOM更新后执行
      nextTick(() => {
        console.log('[GraphAnalysisNew] 显示状态更新:', {
          showKeyMaterials: showKeyMaterials.value,
          showGraph: showGraph.value,
          showSupplyChainVulnerability: showSupplyChainVulnerability.value,
          showSubstituteAnalysis: showSubstituteAnalysis.value
        });
      });
    }, 500); // 增加延迟时间，确保图表能够完全渲染
  } catch (error) {
    console.error('企业风险查询失败:', error);
    ElMessage.error('企业风险查询失败: ' + (error.message || '未知错误'));
    graphLoading.value = false;
    // 清除数据而不是直接修改计算属性
    graphData.value = null; // 这会使showGraph计算属性变为false
  }
};

const handleProductChainQuery = async (params) => {
  if (!params.productName) {
    ElMessage.warning('请输入产品名称');
    return;
  }
  
  // 设置加载状态
  loading.value = true;
  graphLoading.value = true;
  lastProductChainParams.value = params;
  
  try {
    console.log('[GraphAnalysisNew] 查询产品链:', params);
    const result = await getProductChain(params);
    
    // 重置状态 - 只修改源数据，不直接修改计算属性
    keyMaterialsData.value = null;
    supplyChainVulnerabilityData.value = null;
    substituteAnalysisData.value = null;
    statsData.value = null;
    
    // 设置图谱数据展示
    graphData.value = result;
    resultTitle.value = `产品[${params.productName}]技术链图`;
    
    // 增加强制渲染计数，确保视图更新
    forceRender.value += 1;
    
    console.log('[GraphAnalysisNew] 产品链查询成功，数据已更新');
    
    // 使用nextTick确保在DOM更新后记录状态，而不是尝试修改状态
    nextTick(() => {
      console.log('[GraphAnalysisNew] 显示状态更新:', {
        showKeyMaterials: showKeyMaterials.value,
        showGraph: showGraph.value,
        showSupplyChainVulnerability: showSupplyChainVulnerability.value,
        showSubstituteAnalysis: showSubstituteAnalysis.value
      });
    });
  } catch (error) {
    console.error('[GraphAnalysisNew] 产品链查询失败:', error);
    ElMessage.error('产品链查询失败: ' + (error.message || '未知错误'));
    // 清除数据而不是直接修改计算属性
    graphData.value = null;
  } finally {
    // 重置加载状态
    loading.value = false;
    graphLoading.value = false;
  }
};

const handleKeyMaterialsQuery = async () => {
  console.log('[GraphAnalysisNew] 开始关键材料识别查询');
  loading.value = true;
  graphLoading.value = true;
  
  try {
    // 直接调用关键材料识别API，不需要产品参数
    const response = await getKeyMaterials();
    console.log('[GraphAnalysisNew] 关键材料识别响应:', response);
    
    if (response && (Array.isArray(response) || typeof response === 'object')) {
      // 格式化关键材料数据以适配表格组件
      let formattedData = [];
      
      if (Array.isArray(response)) {
        // 如果是数组，直接使用
        formattedData = response;
      } else if (response.keyMaterialsByConnection || response.keyMaterialsByIntermediary) {
        // 如果有特定的对象结构
        // 首先处理连接度数据
        if (Array.isArray(response.keyMaterialsByConnection)) {
          formattedData = response.keyMaterialsByConnection.map(material => ({
            id: material.id,
            name: material.name,
            connectionCount: material.connection_count || material.connectionCount,
            description: `连接度: ${material.connection_count || material.connectionCount}`
          }));
        }
        
        // 处理中介中心性数据并合并
        if (Array.isArray(response.keyMaterialsByIntermediary)) {
          const intermediaryData = response.keyMaterialsByIntermediary.map(material => ({
            id: material.id,
            name: material.name,
            upstreamCount: material.upstream_count || material.upstreamCount,
            downstreamCount: material.downstream_count || material.downstreamCount,
            description: `中介中心性: 上游${material.upstream_count || material.upstreamCount} 下游${material.downstream_count || material.downstreamCount}`
          }));
          
          // 合并两种数据，用连接度数据为主
          const nameSet = new Set(formattedData.map(item => item.name));
          
          intermediaryData.forEach(item => {
            if (!nameSet.has(item.name)) {
              formattedData.push(item);
            } else {
              // 更新已有项的中介数据
              const existingItem = formattedData.find(fi => fi.name === item.name);
              if (existingItem) {
                existingItem.upstreamCount = item.upstreamCount;
                existingItem.downstreamCount = item.downstreamCount;
                existingItem.description = `连接度: ${existingItem.connectionCount}, 上游: ${item.upstreamCount}, 下游: ${item.downstreamCount}`;
              }
            }
          });
        }
      } else {
        // 其他情况，尝试转换为适合表格的格式
        Object.entries(response).forEach(([key, value]) => {
          if (Array.isArray(value)) {
            value.forEach(item => {
              if (item.name) {
                formattedData.push({
                  id: item.id || formattedData.length + 1,
                  name: item.name,
                  connectionCount: item.connection_count || item.connectionCount,
                  upstreamCount: item.upstream_count || item.upstreamCount,
                  downstreamCount: item.downstream_count || item.downstreamCount,
                  description: item.description || `关键材料: ${item.name}`
                });
              }
            });
          }
        });
      }
      
      // 去重
      const uniqueData = [];
      const seen = new Set();
      formattedData.forEach(item => {
        if (!seen.has(item.name)) {
          seen.add(item.name);
          uniqueData.push(item);
        }
      });
      
      // 更新视图状态 - 确保其他视图被隐藏
      // 只修改源数据，不直接修改计算属性
      graphData.value = null; // 清空图表数据，确保不显示图表
      statsData.value = null; // 清空统计数据
      supplyChainVulnerabilityData.value = null; // 清空脆弱性分析数据
      substituteAnalysisData.value = null; // 清空替代分析数据
      
      // 最后设置关键材料数据，因为这会触发showKeyMaterials计算属性变为true
      keyMaterialsData.value = uniqueData;
      console.log('[GraphAnalysisNew] 格式化后的关键材料数据:', keyMaterialsData.value);
      
      // 强制组件重新渲染
      forceRender.value += 1;
      
      // 使用nextTick确保在DOM更新后执行
      nextTick(() => {
        console.log('[GraphAnalysisNew] 关键材料数据已更新，显示状态:', {
          showKeyMaterials: showKeyMaterials.value,
          showGraph: showGraph.value,
          showSupplyChainVulnerability: showSupplyChainVulnerability.value,
          showSubstituteAnalysis: showSubstituteAnalysis.value
        });
      });
    } else {
      ElMessage.warning('未获取到有效的关键材料识别结果');
      keyMaterialsData.value = null;
    }
  } catch (error) {
    console.error('[GraphAnalysisNew] 关键材料识别失败:', error);
    ElMessage.error('关键材料识别失败: ' + (error.message || '未知错误'));
    keyMaterialsData.value = null;
  } finally {
    loading.value = false;
    graphLoading.value = false;
  }
};

const handleProductChainReset = () => {
  resetView();
};

const handleSupplyChainVulnerabilityExport = async (params) => {
  try {
    // 实现供应链脆弱性分析结果导出逻辑
    // 这里需要根据实际需求实现导出逻辑
    console.log('供应链脆弱性分析结果导出:', params);
  } catch (error) {
    console.error('供应链脆弱性分析结果导出失败:', error);
    ElMessage.error('导出失败，请稍后重试');
  }
};

const handleVulnerabilityAnalysis = async () => {
  if (!keyMaterialsData.value) {
    ElMessage.warning('请先进行关键材料识别');
    return;
  }
  
  // 提取需要分析的关键材料名称
  const materials = extractKeyMaterialNames(keyMaterialsData.value);
  
  if (!materials || materials.length === 0) {
    ElMessage.warning('未找到需要分析的关键材料');
    return;
  }
  
  loading.value = true;
  graphLoading.value = true;
  
  try {
    console.log('[GraphAnalysisNew] 分析关键材料的供应链脆弱性:', materials);
    const response = await getSupplyChainVulnerability({ materials });
    
    if (!response) {
      ElMessage.warning('未找到供应链脆弱性数据');
      loading.value = false;
      graphLoading.value = false;
      return;
    }
    
    // 设置供应链脆弱性数据，这会自动使showSupplyChainVulnerability计算属性变为true
    supplyChainVulnerabilityData.value = response;
    console.log('[GraphAnalysisNew] 供应链脆弱性分析结果:', supplyChainVulnerabilityData.value);
    
    // 不直接修改计算属性，而是修改它们依赖的数据
    // 隐藏图表，清空图表数据
    graphData.value = null;
    
    // 清空替代分析数据
    substituteAnalysisData.value = null;
    
    // 增加强制渲染计数，强制视图更新
    forceRender.value += 1;
    
    console.log('[GraphAnalysisNew] 显示状态更新:', {
      showKeyMaterials: showKeyMaterials.value,
      showSupplyChainVulnerability: showSupplyChainVulnerability.value,
      showSubstituteAnalysis: showSubstituteAnalysis.value,
      showGraph: showGraph.value
    });
  } catch (error) {
    console.error('[GraphAnalysisNew] 供应链脆弱性分析失败:', error);
    ElMessage.error('供应链脆弱性分析失败：' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
    graphLoading.value = false;
  }
};

// 从复杂的关键材料数据结构中提取材料名称列表
const extractKeyMaterialNames = (keyMaterialsData) => {
  if (!keyMaterialsData) return [];
  
  // 如果是数组形式
  if (Array.isArray(keyMaterialsData)) {
    return keyMaterialsData.map(item => item.name);
  }
  
  // 如果是对象形式且有keyMaterialsByConnection属性
  if (keyMaterialsData.keyMaterialsByConnection && Array.isArray(keyMaterialsData.keyMaterialsByConnection)) {
    return keyMaterialsData.keyMaterialsByConnection.map(item => item.name);
  }
  
  // 其他格式，尝试提取所有可能的材料名称
  let materials = [];
  
  Object.keys(keyMaterialsData).forEach(key => {
    const value = keyMaterialsData[key];
    if (Array.isArray(value)) {
      const names = value.map(item => item.name).filter(Boolean);
      materials = [...materials, ...names];
    }
  });
  
  // 去重
  return [...new Set(materials)];
};

const handleSubstituteAnalysis = async (materialName) => {
  try {
    substituteAnalysisLoading.value = true;
    
    // 不直接修改计算属性，而是修改其依赖数据
    graphData.value = null; // 这会使showGraph变为false
    
    console.log('[GraphAnalysisNew] 进行替代路径分析:', materialName);
    
    const response = await getSubstituteAnalysis({
      materialName: materialName,
      minSimilarity: 0.3 // 默认相似度阈值
    });

    if (!response || (!response.substitutes || response.substitutes.length === 0)) {
      ElMessage.warning('未找到替代材料数据');
      substituteAnalysisData.value = null;
      substituteAnalysisLoading.value = false;
      return;
    }

    // 保存替代路径分析数据，这会自动触发showSubstituteAnalysis计算属性变为true
    substituteAnalysisData.value = response;
    console.log('[GraphAnalysisNew] 替代路径分析结果:', substituteAnalysisData.value);
    
    // 清空供应链脆弱性数据
    supplyChainVulnerabilityData.value = null;
    
    // 增加强制渲染计数，确保视图更新
    forceRender.value += 1;
    
    console.log('[GraphAnalysisNew] 显示状态更新:', {
      showKeyMaterials: showKeyMaterials.value,
      showSupplyChainVulnerability: showSupplyChainVulnerability.value,
      showSubstituteAnalysis: showSubstituteAnalysis.value,
      showGraph: showGraph.value
    });
    
  } catch (error) {
    console.error('[GraphAnalysisNew] 替代路径分析失败:', error);
    ElMessage.error('分析失败，请稍后重试');
    substituteAnalysisData.value = null;
  } finally {
    substituteAnalysisLoading.value = false;
  }
};

const handleSubstituteAnalysisExport = (data) => {
  try {
    // 导出数据为JSON文件
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `替代材料分析_${data.targetMaterial}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请稍后重试');
  }
};

const returnToProductChain = () => {
  console.log('[GraphAnalysisNew] 返回产品链');
  
  // 清除分析结果数据，这些会间接影响计算属性的值
  keyMaterialsData.value = null; // 这会使showKeyMaterials变为false
  supplyChainVulnerabilityData.value = null;
  substituteAnalysisData.value = null;
  
  // 增加强制渲染计数，确保视图更新
  forceRender.value += 1;
  
  // 如果有图表数据，显示产品链图表
  if (graphData.value) {
    console.log('[GraphAnalysisNew] 使用现有图表数据');
  } else {
    // 如果没有图表数据且有上次查询参数，重新加载
    if (lastProductChainParams.value) {
      console.log('[GraphAnalysisNew] 重新加载上次查询的产品链数据');
      handleProductChainQuery(lastProductChainParams.value);
    } else {
      console.log('[GraphAnalysisNew] 无产品链数据可显示');
    }
  }
  
  console.log('[GraphAnalysisNew] 显示状态更新:', {
    showKeyMaterials: showKeyMaterials.value,
    showSupplyChainVulnerability: showSupplyChainVulnerability.value,
    showSubstituteAnalysis: showSubstituteAnalysis.value,
    showGraph: showGraph.value
  });
};

const returnToKeyMaterials = () => {
  console.log('[GraphAnalysisNew] 返回关键材料识别页面');
  
  // 注意：不要直接修改计算属性的值，而是修改它们依赖的数据源
  
  // 清除替代分析数据和脆弱性分析数据
  substituteAnalysisData.value = null;
  supplyChainVulnerabilityData.value = null;
  
  // 隐藏图表
  graphData.value = null; // 这将导致showGraph计算属性变为false
  
  // 增加强制渲染计数，强制组件重新渲染
  forceRender.value += 1;
  
  // 如果没有关键材料数据，重新调用关键材料识别
  if (!keyMaterialsData.value) {
    console.log('[GraphAnalysisNew] 无关键材料数据，重新获取');
    handleKeyMaterialsQuery();
  } else {
    console.log('[GraphAnalysisNew] 已有关键材料数据，重用现有数据');
    // 为确保视图刷新，先将数据设为null再重新赋值
    const tempData = [...keyMaterialsData.value];
    keyMaterialsData.value = null;
    nextTick(() => {
      keyMaterialsData.value = tempData;
    });
  }
};

// 重置视图状态
const resetView = () => {
  console.log('[GraphAnalysisNew] 重置所有视图状态');
  
  // 只修改源数据，不直接修改计算属性
  graphData.value = null; // 会导致showGraph计算属性变为false
  statsData.value = null; 
  keyMaterialsData.value = null; // 会导致showKeyMaterials计算属性变为false
  supplyChainVulnerabilityData.value = null; // 会导致showSupplyChainVulnerability计算属性变为false
  substituteAnalysisData.value = null; // 会导致showSubstituteAnalysis计算属性变为false
  
  resultTitle.value = '';
  
  // 增加强制渲染计数，确保视图更新
  forceRender.value += 1;
  
  console.log('[GraphAnalysisNew] 视图状态已重置');
};
</script>

<style scoped>
.graph-analysis-container {
  padding: 15px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 120px);
}

/* 现代化顶部标签页样式 */
.main-tabs-container {
  margin-bottom: 30px;
  padding: 0;
  background: linear-gradient(135deg, #f0f2f5 0%, #e6e9f0 100%);
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.07);
  position: relative;
  overflow: hidden;
}

.main-tabs-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.8), transparent);
  z-index: 1;
}

.main-tabs-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  padding: 6px;
  position: relative;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
}

.main-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 14px 10px;
  border-radius: 10px;
  font-size: 15px;
  font-weight: 500;
  color: var(--el-text-color-secondary);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  gap: 10px;
  z-index: 1;
  margin: 0 3px;
}

.main-tab::after {
  content: '';
  position: absolute;
  bottom: -3px;
  left: 50%;
  width: 0;
  height: 3px;
  background: var(--el-color-primary);
  transition: all 0.3s ease;
  transform: translateX(-50%);
  opacity: 0;
  border-radius: 3px;
}

.main-tab:hover:not(.active) {
  color: var(--el-color-primary);
  background-color: rgba(var(--el-color-primary-rgb), 0.05);
}

.main-tab:hover:not(.active)::after {
  width: 30%;
  opacity: 0.5;
}

.main-tab.active {
  color: white;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
  box-shadow: 0 6px 15px rgba(var(--el-color-primary-rgb), 0.25);
  transform: translateY(-1px);
}

.main-tab.active::after {
  width: 70%;
  opacity: 1;
}

.tab-icon {
  font-size: 20px;
  flex-shrink: 0;
}

.tab-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 主内容布局样式 */
.main-content-layout {
  display: flex;
  gap: 20px;
  height: calc(100% - 64px);
}

.query-card {
  flex: 0 0 300px;
  min-width: 270px;
  max-width: 360px;
  overflow-y: auto;
  height: fit-content;
  border-radius: 12px;
  border: none;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.query-card:hover {
  box-shadow: 0 12px 36px rgba(0, 0, 0, 0.08);
}

.graph-card {
  flex: 1;
  min-height: 600px;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  border: none;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  overflow: hidden;
}

.graph-card:hover {
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.08);
}

/* 加载状态样式 */
.loading-placeholder {
  padding: 30px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
}

/* 分析操作按钮样式 */
.analysis-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  padding: 5px;
}

.analysis-actions .el-button {
  margin-left: 12px;
  border-radius: 8px;
  padding: 10px 16px;
  transition: all 0.3s ease;
}

.analysis-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.key-materials-button,
.vulnerability-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-weight: 500;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .main-content-layout {
    flex-direction: column;
  }

  .query-card {
    flex: 0 0 auto;
    max-width: 100%;
    min-width: 100%;
    margin-bottom: 20px;
  }

  .graph-card {
    min-height: 500px;
  }
}

@media (max-width: 768px) {
  .main-tab {
    padding: 12px 8px;
    font-size: 13px;
    flex-direction: column;
    gap: 5px;
  }
  
  .tab-icon {
    font-size: 18px;
  }
  
  .analysis-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .analysis-actions .el-button {
    margin-left: 0;
    margin-top: 5px;
  }
}
</style> 